import { BaseUrl } from "./config";
import qs from "qs";
interface Config extends RequestInit {
  method: string;
  data?: { [key: string]: unknown };
  // token?: string | null;
}

export const http = (
  urlData: string,
  {
    data,
    // token,
    headers,
    ...customConfig
  }: Config = { method: "GET" }
) => {
  const config = {
    headers: {
      // Authorization: token ? `Bearer ${token}` : "",
      // "Content-Type": data ? "application/json" : "",
      "Content-Type": "application/json",
    },
    ...customConfig,
  };
  let url = `${BaseUrl}${urlData}`;

  switch (config.method.toUpperCase()) {
    case "POST":
    case "PUT":
      config.body = JSON.stringify(data || {});
      break;
    default:
      url += `?${qs.stringify(data)}`;
      break;
  }



  return window.fetch(`${url}`, config).then(async (response) => {
    const data = await response.json();
    if (response.ok) {
      return data;
    } else {
      return Promise.reject(data);
    }
  });
};